package com.yc.cloud.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yc.cloud.admin.dto.mediakit.MediaKitOnPublishHook;
import com.yc.cloud.admin.dto.mediakit.MediaKitOnPublishResponse;
import com.yc.cloud.admin.service.PublishAuthService;
import com.yc.cloud.entity.HwDevice;
import com.yc.cloud.mapper.HwDeviceMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 推流鉴权服务实现类
 * </p>
 *
 * @author kinggu
 * @since 2025-01-03
 */
@Service
@Slf4j
public class PublishAuthServiceImpl implements PublishAuthService {

    @Resource
    private HwDeviceMapper hwDeviceMapper;

    @Override
    public MediaKitOnPublishResponse processPublishAuth(MediaKitOnPublishHook payload) {
        try {
            log.info("Processing publish auth: app={}, stream={}, ip={}, schema={}", 
                    payload.getApp(), payload.getStream(), payload.getIp(), payload.getSchema());

            // 1. 基本参数验证
            if (StrUtil.isEmpty(payload.getStream())) {
                log.warn("Publish denied: empty stream ID");
                return MediaKitOnPublishResponse.deny("流ID不能为空");
            }

            // 2. 检查应用名是否为live（根据我们的配置）
            // if (!"live".equals(payload.getApp())) {
            //     log.warn("Publish denied: invalid app name: {}", payload.getApp());
            //     return MediaKitOnPublishResponse.deny("无效的应用名");
            // }

            // 3. 验证设备是否存在且有权限推流
            // boolean deviceAuthorized = checkDeviceAuthorization(payload.getStream());
            // if (!deviceAuthorized) {
            //     log.warn("Publish denied: device not authorized for stream: {}", payload.getStream());
            //     return MediaKitOnPublishResponse.deny("设备未授权或不存在");
            // }

            // 4. 可以添加其他鉴权逻辑，比如：
            // - IP白名单检查
            // - 推流时间限制
            // - 并发推流数量限制
            // - 设备状态检查等

            // 5. 允许推流，并配置录制参数
            log.info("Publish allowed for stream: {}, device authorized", payload.getStream());
            return MediaKitOnPublishResponse.allowWithConfig(true); // 启用录制

        } catch (Exception e) {
            log.error("Error processing publish auth: stream={}", payload.getStream(), e);
            return MediaKitOnPublishResponse.deny("系统错误，请稍后重试");
        }
    }

    // /**
    //  * 检查设备是否有推流授权
    //  * @param stream 流ID，格式：sipUsername_videoChannel
    //  * @return 是否授权
    //  */
    // private boolean checkDeviceAuthorization(String stream) {
    //     try {
    //         if (StrUtil.isEmpty(stream)) {
    //             return false;
    //         }

    //         // 解析stream，格式：sipUsername_videoChannel
    //         String[] parts = stream.split("_");
    //         if (parts.length != 2) {
    //             log.warn("Invalid stream format, expected sipUsername_videoChannel: {}", stream);
    //             return false;
    //         }

    //         String sipUsername = parts[0];
    //         String videoChannel = parts[1];

    //         // 查询设备是否存在且未删除
    //         HwDevice device = hwDeviceMapper.selectOne(
    //                 new QueryWrapper<HwDevice>()
    //                         .eq(HwDevice.SipUsername, sipUsername)
    //                         .eq(HwDevice.VideoChannel, videoChannel)
    //                         .eq(HwDevice.Deleted, false)
    //         );

    //         if (device == null) {
    //             log.warn("Device not found for stream: {}, sipUsername={}, videoChannel={}", 
    //                     stream, sipUsername, videoChannel);
    //             return false;
    //         }

    //         // 检查设备状态（可选）
    //         if (device.getStatus() != null && device.getStatus() == 0) {
    //             log.warn("Device is offline, denying push: deviceId={}, stream={}", 
    //                     device.getId(), stream);
    //             return false;
    //         }

    //         log.info("Device authorization successful: deviceId={}, deviceName={}, stream={}", 
    //                 device.getId(), device.getName(), stream);
    //         return true;

    //     } catch (Exception e) {
    //         log.error("Failed to check device authorization for stream: {}", stream, e);
    //         return false;
    //     }
    // }

    /**
     * 检查IP是否在白名单中（示例方法）
     */
    @SuppressWarnings("unused")
    private boolean checkIpWhitelist(String ip) {
        // 可以从配置文件或数据库读取IP白名单
        // 这里先简单实现，允许所有内网IP
        if (StrUtil.isEmpty(ip)) {
            return false;
        }
        
        return ip.startsWith("192.168.") || 
               ip.startsWith("10.") || 
               ip.startsWith("172.") ||
               ip.equals("127.0.0.1");
    }

    /**
     * 检查推流时间限制（示例方法）
     */
    @SuppressWarnings("unused")
    private boolean checkTimeLimit() {
        // 可以实现推流时间窗口限制
        // 比如只允许在工作时间推流
        return true;
    }
}
